package br.org.underserver.server;
/**
 * @author alexandre.araujo
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import br.org.underserver.resposta.Response;
import br.org.underserver.resposta.ResponseFactory;
import br.org.underserver.resquisicao.Request;
import br.org.underserver.servidor.ServerHTTP;

public class VirtualServer implements Runnable{
    @Override
    public void run(){
            //ServerHTTP.addInfo("Estou sendo executado pela Thread de nome: " + Thread.currentThread().getName());
           
            ServerSocket serverSocket = null;

		ServerHTTP.addInfo("Iniciando servidor no endereço: " + ServerHTTP.getInstancia().getHost() + ":" + ServerHTTP.getInstancia().getPort());		
		
		try {
			// Cria a conexão servidora
			serverSocket = new ServerSocket(ServerHTTP.getInstancia().getPort(), 1,	InetAddress.getByName(ServerHTTP.getInstancia().getHost()));
		} catch (IOException e) {
			ServerHTTP.addInfo("Erro ao iniciar servidor!:"+e.getMessage().toString());
			return;
		}
		ServerHTTP.addInfo("Conexão com o servidor aberta no endereço: " + ServerHTTP.getInstancia().getHost()
				+ ":" + ServerHTTP.getInstancia().getPort());

		// Fica esperando pela conexão cliente
                
                
                try {
                 
   while (!Thread.interrupted()) {
       			ServerHTTP.addInfo("\nAguardando conexões...\n");
			Socket socket = null;
			InputStream input = null;
			OutputStream output = null;
			try {
				socket = serverSocket.accept();
				input = socket.getInputStream();
				output = socket.getOutputStream();
				// Realiza o parse da requisição recebida
				String requestString = convertStreamToString(input);
				ServerHTTP.addInfo("Conexão recebida. Conteúdo:\n" + requestString);
                                //ServerHTTP.addInfo("\nFim Conteiudo\n");
				Request request = new Request();
				request.parse(requestString);
				// recupera a resposta de acordo com a requisicao
				Response response = ResponseFactory.createResponse(request);                               
				String responseString = response.respond();
				//this.info("Resposta enviada. Conteúdo:\n" + responseString);
				output.write(responseString.getBytes());
				// Fecha a conexão
				socket.close();
			} catch (Exception e) {
				ServerHTTP.addInfo("Erro ao executar servidor!:"+e.getMessage().toString());
				continue;
			}
                   }
                } catch (Exception e) {
                    ServerHTTP.addInfo("Erro ao encerrar servidor: " + e.getMessage().toString());
                }
    }
     private String convertStreamToString(InputStream is) {
                String rt = "";
		if (is != null) {
			Writer writer = new StringWriter();
			char[] buffer = new char[2048];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is));
				int i = reader.read(buffer);
				writer.write(buffer, 0, i);
			} catch (IOException e) {
				ServerHTTP.addInfo("Erro ao converter stream para string:"+e.getMessage().toString());
				rt = "";
			}
			rt = writer.toString();
		}
                return rt;
	}
}